package com.pkche.core.advanced.util.aliyun;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

/**
 * 阿里云OSS相关java API
 * @author yc
 *
 */
public class AliyunOssUtil {
	 /**
	  *  创建Bucket.
	  * @param client
	  * @param bucketName
	  * @throws com.aliyun.oss.OSSException
	  * @throws com.aliyun.oss.ClientException
	  */
    public static void ensureBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException{

        try {
            // 创建bucket
            client.createBucket(bucketName);
        } catch (ServiceException e) {
            if (!OSSErrorCode.BUCKES_ALREADY_EXISTS.equals(e.getErrorCode())) {
                // 如果Bucket已经存在，则忽略
                throw e;
            }
        }
    }

   /**
    *  删除一个Bucket和其中的Objects 
    * @param client
    * @param bucketName
    * @throws com.aliyun.oss.OSSException
    * @throws com.aliyun.oss.ClientException
    */
    public static void deleteBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException {

        ObjectListing ObjectListing = client.listObjects(bucketName);
        List<OSSObjectSummary> listDeletes = ObjectListing
                .getObjectSummaries();
        for (int i = 0; i < listDeletes.size(); i++) {
            String objectName = listDeletes.get(i).getKey();
            // 如果不为空，先删除bucket下的文件
            client.deleteObject(bucketName, objectName);
        }
        client.deleteBucket(bucketName);
    }

    /**
     *  把Bucket设置为所有人可读
     * @param client
     * @param bucketName
     * @throws com.aliyun.oss.OSSException
     * @throws com.aliyun.oss.ClientException
     */
    public static void setBucketPublicReadable(OSSClient client, String bucketName)
            throws OSSException, ClientException {
        //创建bucket
        client.createBucket(bucketName);

        //设置bucket的访问权限，public-read-write权限
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    }

    /**
     *  上传文件
     * @param client
     * @param bucketName
     * @param key
     * @param filename
     * @param contentType default "image/gif"
     * @throws com.aliyun.oss.OSSException
     * @throws com.aliyun.oss.ClientException
     * @throws java.io.FileNotFoundException
     */
    public static String uploadFile(OSSClient client, String bucketName, String key, String filename,String contentType)
            throws OSSException, ClientException, FileNotFoundException {
        File file = new File(filename);
        contentType = contentType == null ? "image/gif" : contentType;
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());
        objectMeta.setContentType(contentType);
        InputStream input = new FileInputStream(file);
        PutObjectResult result =  client.putObject(bucketName, key, input, objectMeta);
        return result.getETag();
    }

    /**
     * 下载文件
     * @param client
     * @param bucketName
     * @param key
     * @param filename
     * @throws com.aliyun.oss.OSSException
     * @throws com.aliyun.oss.ClientException
     */
    public static void downloadFile(OSSClient client, String bucketName, String key, String filename)
            throws OSSException, ClientException {
        client.getObject(new GetObjectRequest(bucketName, key),
                new File(filename));
    }
    
    /**
     * 创建一个文件夹
     * @param client
     * @param bucketName
     * @param folderPah
     */
    public static void createFolder(OSSClient client,String bucketName,String folderPah){
		ObjectMetadata objectMeta = new ObjectMetadata();
		byte[] buffer = new byte[0];
		ByteArrayInputStream in = new ByteArrayInputStream(buffer);  
		objectMeta.setContentLength(0);
		try {
		    client.putObject(bucketName, folderPah, in, objectMeta);
		}catch(Exception e){
			e.printStackTrace();
		} finally {
		    try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
    }
}
